package br.com.fiap.mercadinho.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.fiap.mercadinho.bean.User;
import br.com.fiap.mercadinho.common.RequestKey;
import br.com.fiap.mercadinho.common.ServiceException;
import br.com.fiap.mercadinho.common.SessionKey;
import br.com.fiap.mercadinho.dao.UserDAO;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		throw new ServletException("Method Get is not Supported for this operation");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			UserDAO dao = new UserDAO();
			String login = request.getParameter("login");
			String password = request.getParameter("password");
			
			User user;
			user = dao.findUserByLoginAndPass(login, password);

			if (user != null) {
				request.getSession().setAttribute(SessionKey.USER_SESSION_KEY.getValue(), user);
				request.getSession().setAttribute(SessionKey.USER_SESSION_TYPE.getValue(), user.getUserType().getValue());
				request.getRequestDispatcher("main.jsp").forward(request, response);
				return;
			}else{
				request.setAttribute(RequestKey.INFO_MESSAGE_KEY.getValue(), "Usuario e/ou senha estao incorretos!");
				request.getRequestDispatcher("login.jsp").forward(request, response);
				return;
			}

		} catch (Exception e) {
			throw new ServiceException("Erro ao tentar autenticar o usuario: " + e.getMessage());
		}
	
	}

	
}
